<template>
  <div>
    <el-drawer
      v-model="prop.isTitle"
      :title="'试题' + prop.title"
      size="50%"
      :close-on-click-modal="false"
      :before-close="close"
    >
      <div class="drawer">
        <!-- 单选按钮 -->
        <div class="radio">
          <el-radio-group
            v-model="params.type"
            @change="changeRadio"
          >
            <el-radio label="单选题" size="large">单选题</el-radio>
            <el-radio label="多选题" size="large">多选题</el-radio>
            <el-radio label="判断题" size="large">判断题</el-radio>
            <el-radio label="填空题" size="large">填空题</el-radio>
            <el-radio label="问答题" size="large">问答题</el-radio>
          </el-radio-group>
        </div>
        <div class="conent">
          <el-form :model="data" class="demo-form-inline" label-width="80px">
            <!-- 编辑器开始 -->
            <el-form-item label="题干">
              <div style="border: 1px solid #ccc">
                <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                />
                <Editor
                  style="height: 130px; overflow-y: hidden"
                  v-model="params.title"
                  :defaultConfig="editorConfig"
                  mode="default"
                  @onCreated="handleCreated"
                />
              </div>
            </el-form-item>
            <!-- 编辑器结束 -->
            
            <!-- 选项和文本框删除按钮 -->
            <el-form-item
            label="选项"
            v-show="params.type == '单选题' || params.type == '多选题'"
          >
            <div
              class="option"
              v-for="(item, index) in params.answers"
              :key="index"
            >
              <span>{{ arr[index] }}：</span>
              <el-input v-model="item.content" type="textarea" />
              <el-icon
                ><CircleClose class="font" @click.prevent="removeDomain(item)"
              /></el-icon>
            </div>
          </el-form-item>

          <!-- 添加按钮 -->
          <el-form-item
            v-show="params.type == '单选题' || params.type == '多选题'"
          >
            <el-icon @click="addDomain"><CirclePlus class="fonts" /></el-icon>
          </el-form-item>

          <!-- 单选题 -->
          <el-form-item
            label="正确答案"
            v-show="params.type == '单选题'"
            style="margin-top: 10px"
          >
            <el-radio-group
              v-model="params.answer"
              v-for="(item, index) in params.answers"
              :key="index"
            >
              <el-radio :label="arr[index]" size="large"></el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 多选题 -->
          <el-form-item
            label="正确答案"
            v-show="params.type == '多选题'"
            style="margin-top: 10px"
          >
            <el-checkbox-group
              v-for="(item, index) in params.answers"
              v-model="check"
              @change="changeCheckbox"
              :key="index"
            >
              <el-checkbox :label="arr[index]" size="large" />
            </el-checkbox-group>
          </el-form-item>

          <!-- 判断题 -->
          <el-form-item
            label="正确答案"
            v-show="params.type == '判断题'"
            style="margin-top: 10px"
          >
            <el-radio-group v-model="params.answer" size="large">
              <el-radio-button label="正确" />
              <el-radio-button label="错误" />
            </el-radio-group>
          </el-form-item>

          <!-- 填空题 -->
          <el-form-item
            label="正确答案"
            label-width="90px"
            style="max-width: 460px"
            v-if="topicArr.length > 0"
            v-show="params.type == '填空题'"
          >
            <div class="from">
              <el-input
                v-model="topicArr[index]"
                v-for="(item, index) in topicArr"
                :key="index"
                v-show="params.type == '填空题'"
              />
            </div>
          </el-form-item>
          
          <!-- 填空题的分析 -->
          <el-form-item label="解析" v-show="params.type == '填空题'">
            <el-input
              v-model="params.explains"
              type="textarea"
              style="margin-left: 0px"
            />
          </el-form-item>

          <!-- 问答题 -->
          <el-form-item label="解析" v-show="params.type == '问答题'">
            <el-input
              v-model="params.explains"
              type="textarea"
              style="margin-left: 0px"
            />
          </el-form-item>

          <!-- 分值 -->
          <el-form-item label="分值">
            <div class="score">
              <el-input v-model="params.scores" />
            </div>
          </el-form-item>
          </el-form>
          
          <!-- 按钮 -->
          <div class="but">
          <el-button type="primary" @click="save">保存</el-button>
          <el-button
            >保存并继续</el-button
          >
          <el-button @click="cancel">取消</el-button>
        </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import {
  reactive,
  toRefs,
  watch,
  defineEmits,
  computed,
  shallowRef,
} from 'vue';
// 引入编辑器
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { ElMessage } from "element-plus";
import { CircleClose, CirclePlus } from '@element-plus/icons-vue'; // icon
const emit = defineEmits(['isClose','addSave']);//子传父
// const props: any = defineProps({//父传子
//   isTitle: Boolean,
// });
const prop = defineProps(['isTitle','title']); //父向子传值

const close = () => {
  emit('isClose', false);
};
const data: any = reactive({
  // drawer: false,
  // 多选框
  check: <any>[],
  params: {
    // 正确答案
    answer: <any>null,
    // 类型
    type: "单选题",
    scores: "",
    // 在线编辑器
    title: "",
    tags: "",
    // 答案解析
    explains: "",
    answers: [
      { answerno: "A", content: "" },
      { answerno: "B", content: "" },
      { answerno: "C", content: "" },
      { answerno: "D", content: "" },
    ],
  },
  arr: [
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
  ],
  topicArr: [],
 
});
const { topicArr, drawer, params, arr, check }: any = toRefs(data);

// 保存
const save = ()=>{
  if (params.value.type === "单选题" || params.value.type === "多选题") {
    if (!params.value.answer) {
      ElMessage("正确答案必填！");
      return;
    } else if (!params.value.scores) {
      ElMessage("请输入分值");
      return;
    }
    var noNum: number = 0;
    params.value.answers.map((item: any) => {
      if (!item.content) {
        noNum += 1;
      }
    });
    if (noNum > 0) {
      ElMessage("选项答案必填！");
      return;
    }
  }
  if (params.value.type === "判断题") {
    if (!params.value.answer) {
      ElMessage("请输入正确答案");
      return;
    }
    if (!params.value.scores) {
      ElMessage("请输入分值");
      return;
    }
  }

  if (params.value.type === "填空题" || params.value.type === "问答题") {
    params.value.answer = data.topicArr.join("|");
    if (!params.value.scores) {
      ElMessage("请输入分值");
      return;
    }
  }
  console.log(params.value);
    if(params.value.type === "单选题"){
    emit('addSave', false, params.value); //数据传给父组件
  }
  if(params.value.type === "多选题"){
    emit('addSave', false, params.value); //数据传给父组件
  }
  if(params.value.type === "判断题"){
    emit('addSave', false, params.value); //数据传给父组件
  }
  if(params.value.type === "填空题"){
    emit('addSave', false, params.value); //数据传给父组件
  }
  if(params.value.type === "问答题"){
    emit('addSave', false, params.value); //数据传给父组件
  }
}

// 取消
const cancel = () => {
  check.value = [];
  data.topicArr = [];
  emit("isClose", false);
};

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const toolbarConfig = {
  toolbarKeys: [
    // 菜单 key
    'bold',
    'italic',
    'underline',
    'through',
    'color',
    'bgColor',
    'bulletedList',
    'numberedList',
    'justifyLeft',
    'justifyCenter',
    'justifyRight',
    'insertTable',
    // 继续配置其他菜单...
    {
      key: 'group-image', // 必填，要以 group 开头
      title: '图片', // 必填
      menuKeys: ['uploadImage', 'insertImage'],
    },
  ],
};
const uploadImg = 'http://www.eshareedu.cn/exam/api/upload/editeradd'//上传图片的地址
const editorConfig: any = { MENU_CONF: {} };
editorConfig.MENU_CONF['uploadImage'] = {
  server: uploadImg, // 上传图片地址
  timeout: 5 * 1000, // 5s
  fieldName: 'file',
  meta: { baseUrl: '' },
  metaWithUrl: true, // 参数拼接到 url 上
  headers: { Authorization: sessionStorage.getItem('token') },

  maxFileSize: 10 * 1024 * 1024, // 10M

  base64LimitSize: 5 * 1024, // 5kb 以下插入 base64

  onBeforeUpload(files: any) {
    console.log('onBeforeUpload', files);
    return files; // 返回哪些文件可以上传
  },
  onProgress(progress: any) {
    console.log('onProgress', progress);
  },
  onSuccess(file: any, res: any) {
    console.log('onSuccess', file, res);
  },
  onFailed(file: any, res: any) {
    alert(res.message);
    console.log('onFailed', file, res);
  },
  onError(file: any, err: any, res: any) {
    alert(err.message);
    console.error('onError', file, err, res);
  },
  // // 用户自定义插入图片
  customInsert(res: any, insertFn: any) {
    var Img = res.data[0].url.slice(1);
    // 自己插入图片
    // console.log('自己插入图片', url)
    // insertFn(url, alt, href)
    insertFn('http://www.eshareedu.cn/exam/upload/' + Img);
  },
};
const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
// 单选框内容改变
const changeRadio = (e: any) => {
  params.value.answer = "";
  params.value.explains = "";
  params.value.answers.map((item: any) => (item.content = ""));
};
// 删除
const removeDomain = (item: any) => {
  const index = params.value.answers.indexOf(item);
  if (index !== -1) {
    params.value.answers.splice(index, 1);
  }
};
// 点击加号加一
const addDomain = () => {
  if (data.arr.length === params.value.answers.length) {
    ElMessage("已经到底了！");
    return;
  }
  params.value.answers.push({
    answerno: arr.value[params.value.answers.length],
  });
};

// 多选框内容改变
const changeCheckbox = (e: any) => {
  data.params.answer = e;
};
</script>

<style lang="less" scoped>
.drawer {
  .radio {
    padding: 0px 30px;
    margin-top: -30px;
  }

  .conent {
    padding: 15px 0px 15px 10px;
    :deep(.el-textarea__inner) {
      height: 33px;
    }

    :deep(.el-textarea) {
      margin-bottom: 18px;
    }

    .option {
      display: flex;
      :deep(.el-textarea__inner) {
        height: 32px;
        width: 400px;
        font-size: 13px;
      }
      :deep(.el-icon) {
        font-size: 20px;
        margin-left: 11px;
        margin-top: 5px;
      }
      :deep(.el-icon) {
        font-size: 22px;
        margin-left: 6px;
        color: #f56c6c;
      }
    }

    .el-icon {
      font-size: 30px;
      margin-left: 26px;
      margin-top: -16px;
    }

    .fonts {
      color: #48a2ff;
    }

    .score {
      :deep(.el-input) {
        width: 77px;
        height: 28px;
      }
    }

    .but {
      padding-left: 80px;
    }

    ::v-deep .el-radio-button:first-child .el-radio-button__inner {
      font-size: 13px;
    }

    ::v-deep .el-radio-button:last-child .el-radio-button__inner {
      font-size: 13px;
    }

    ::v-deep .el-radio-group {
      margin-top: -3px;
      // margin-left: 10px;
    }

    ::v-deep .el-radio:last-child {
      margin-right: 11px;
    }

    ::v-deep .el-checkbox:last-of-type {
      margin-right: 11px;
    }

    ::v-deep .from {
      .el-input {
        width: 230px;
        margin-bottom: 6px;
      }
    }
  }
}
</style>
